// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-15

package remove

import (
	"context"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
	"server/app/lib"
)

// Logic
// 删除轮播图.
type Logic struct {
	admin  *models.ArcadeAdmins
	arcade *models.Arcades

	affects     int64
	kind        kind.ArcadeAdminOperation
	kindContent string
	swiper      *models.ArcadeSwiper

	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// After
// 后置日志.
func (o *Logic) After(ctx context.Context, _ iris.Context, _ result.Result) {
	if o.affects > 0 {
		_, _ = services.NewArcadeLogsService().Add(ctx,
			o.arcade, o.admin, o.kind, o.kindContent,
		)
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Json(i, o.request); err == nil {
		o.arcade, o.admin = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err error
		res = result.New()
	)
	if err = db.Transaction(ctx, o.RunSelect, o.RunRemove); err != nil {
		return res.WithError(err)
	}
	return res.With(o.response)
}

// RunSelect
// 查询数据.
func (o *Logic) RunSelect(ctx context.Context, sess *db.Session) (err error) {
	var has bool
	if o.swiper, has, err = services.NewArcadeSwiperService(sess).Dao.GetById(ctx, o.request.Id); err != nil {
		err = errs.ErrDatabaseQuery
	} else if !has || o.swiper.ArcadeId != o.arcade.Id {
		err = errs.ErrArcadeSwiperNotFound
	}
	return
}

func (o *Logic) RunRemove(ctx context.Context, sess *db.Session) (err error) {
	if o.affects, err = services.NewArcadeSwiperService(sess).Dao.DeleteById(ctx, o.swiper.Id); err != nil {
		err = errs.ErrDatabaseQuery
	} else {
		o.kind = kind.ArcadeAdminOperationSwiperDelete
		o.kindContent = o.kind.ToSwiperDelete(o.swiper.Title, o.swiper.Enabled)
	}
	return
}
